package com.panda.web.service.wechatinfo.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panda.web.domain.dto.wechatinfo.UserinfoDTO;
import com.panda.web.domain.vo.commons.AddressVO;
import com.panda.web.domain.vo.wechatinfo.UserinfoVO;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.entity.wechatinfo.*;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.mapper.wechatinfo.*;
import com.panda.web.service.wechatinfo.IWechatUserinfoService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.*;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户个人信息Service业务层处理
 *
 * @author cpanda
 * @date 2025-03-04
 */
@Slf4j
@Service
public class WechatUserinfoServiceImpl extends ServiceImpl<WechatUserinfoMapper, WechatUserinfo> implements IWechatUserinfoService {
    @Autowired
    WechatUserinfoMapper userinfoMapper;
    @Autowired
    UserMotherMapper motherMapper;
    @Autowired
    UserFatherMapper fatherMapper;
    @Autowired
    UserHonorMapper honorMapper;
    @Autowired
    UserProjectMapper projectMapper;
    @Autowired
    UserEducationMapper educationMapper;
    @Autowired
    UserSchoolgoMapper schoolgoMapper;
    @Autowired
    UserScientificResearchMapper scientificResearchMapper;
    @Autowired
    UserSkillMapper userSkillMapper;
    @Autowired
    UserDemandMapper demandMapper;
    @Autowired
    WechatUserMapper userMapper;

    @Autowired
    UserMajorRgppMapper majorRgppMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<UserinfoVO> PageList(UserinfoDTO dto, Integer pageNum, Integer pageSize) {

        Page<WechatUserinfo> page = new Page<>(pageNum, pageSize);
        QueryWrapper<WechatUserinfo> queryWrapper = new QueryWrapper();//需要处理查询条件

        if (!Objects.equals(dto.getName(), null)) {
            queryWrapper.like("name", dto.getName());
        }
        queryWrapper.orderByDesc("create_time");
        IPage<WechatUserinfo> userinfoIPage = userinfoMapper.selectPage(page, queryWrapper);
        long total = userinfoIPage.getTotal();
        List<WechatUserinfo> records = userinfoIPage.getRecords();

        List<UserinfoVO> voList = userinfoVoToList(records);//封装vo数据方法
      
        return new PageResult<>(voList, total, pageNum, pageSize);
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<UserinfoVO> choiceList(UserinfoDTO dto) {
        QueryWrapper<WechatUserinfo> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<WechatUserinfo> userinfoList = userinfoMapper.selectList(queryWrapper);
        List<UserinfoVO> voList = userinfoVoToList(userinfoList);//封装vo数据方法
        return voList;
    }

    /**
     * 回显数据
     *
     * @param openid
     * @return
     */
    @Override
    public UserinfoVO selectById(String openid) {
        UserinfoVO vo = new UserinfoVO();
        WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
        if (userinfo == null) {
            return vo; // 如果 userinfo 为 null，直接返回空的 UserinfoVO
        }
        BeanUtils.copyProperties(userinfo, vo);
        WechatUser wechatUser = userMapper.findByOpenId(userinfo.getOpenid());
        vo.setHeadimgurl(wechatUser.getHeadimgurl());
        vo.setNickName(wechatUser.getNickname());
        List<UserMajorRgpp> userMajorRgppList = majorRgppMapper.findByOpenid(openid);
        vo.setUserMajorRgppList(userMajorRgppList);
        List<UserMother> motherList = motherMapper.findByOpenid(openid);
        List<UserHonor> honorList = honorMapper.findByOpenid(openid);
        List<UserProject> projectList = projectMapper.findByOpenid(openid);
        List<UserEducation> educationList = educationMapper.findByOpenid(openid);
        List<UserSchoolgo> schoolgoList = schoolgoMapper.findByOpenid(openid);
        List<UserScientificResearch> researchList = scientificResearchMapper.findByOpenid(openid);
        List<UserSkill> skillList = userSkillMapper.findByOpenid(openid);
        List<UserFather> fatherList = fatherMapper.findByOpenid(openid);
        List<UserDemand> demandList = demandMapper.findByOpenid(openid);
        vo.setDemandList(demandList);
        vo.setFatherList(fatherList);
        vo.setEducationList(educationList);
        vo.setHonorList(honorList);
        vo.setMotherList(motherList);
        vo.setProjectList(projectList);
        vo.setSchoolgoList(schoolgoList);
        vo.setResearchList(researchList);
        vo.setSkillList(skillList);
        return vo;
    }

    /**
     * 新增
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public synchronized int insert(UserinfoDTO dto) {
        String openid = dto.getOpenid();//用户唯一id
        WechatUserinfo userinfo1 = userinfoMapper.findByOpenid(openid);
        if (userinfo1!=null){
            //已存在info
            userinfoMapper.updateById(userinfo1);
        }else {
            WechatUserinfo userinfo = new WechatUserinfo();
            BeanUtils.copyProperties(dto, userinfo);
            userinfo.setOpenid(openid);
            userinfo.setCreateTime(new Date());
            userinfo.setUpdateTime(new Date());

            //添加用户其他信息
            addUserInfoQTXX(dto, openid);
            userinfoMapper.insert(userinfo);
        }

        WechatUser wechatUser = userMapper.findByOpenId(openid);
        wechatUser.setUserinfoStatus("1");
        userMapper.updateById(wechatUser);
        return 1;
    }

    //添加用户其他信息
    private void addUserInfoQTXX(UserinfoDTO dto, String openid) {
        //处理专业
        List<UserMajorRgpp> userMajorRgppList = dto.getUserMajorRgppList();
        if (userMajorRgppList!=null&&!userMajorRgppList.isEmpty()){
            for (UserMajorRgpp userMajorRgpp : userMajorRgppList) {
                userMajorRgpp.setOpenid(openid);
                majorRgppMapper.insert(userMajorRgpp);
            }
        }else {
            throw new RuntimeException("请填写专业");
        }

        List<UserDemand> demandList = dto.getDemandList();
        if (demandList != null && !demandList.isEmpty()) {
            for (UserDemand demand : demandList) {
                demand.setOpenid(openid);
                demandMapper.insert(demand);
            }
        }else {
            throw new RuntimeException("请填写求职需求");
        }


        List<UserFather> fatherList = dto.getFatherList();
        if (fatherList != null && !fatherList.isEmpty()) {
            for (UserFather father : fatherList) {
                father.setOpenid(openid);
                fatherMapper.insert(father);
            }
        }

        List<UserMother> motherList = dto.getMotherList();
        if (motherList != null && !motherList.isEmpty()) {
            for (UserMother userMother : motherList) {
                userMother.setOpenid(openid);
                motherMapper.insert(userMother);
            }
        }
        List<UserHonor> honorList = dto.getHonorList();
        if (honorList != null && !honorList.isEmpty()) {
            for (UserHonor userHonor : honorList) {
                userHonor.setOpenid(openid);
                honorMapper.insert(userHonor);
            }
        }
        List<UserEducation> educationList = dto.getEducationList();
        if (educationList != null && !educationList.isEmpty()) {
            for (UserEducation userEducation : educationList) {
                userEducation.setOpenid(openid);
                educationMapper.insert(userEducation);
            }
        }
        List<UserProject> projectList = dto.getProjectList();
        if (projectList != null && !projectList.isEmpty()) {
            for (UserProject userProject : projectList) {
                userProject.setOpenid(openid);
                projectMapper.insert(userProject);
            }
        }
        List<UserSchoolgo> schoolgoList = dto.getSchoolgoList();
        if (schoolgoList != null && !schoolgoList.isEmpty()) {
            for (UserSchoolgo userSchoolgo : schoolgoList) {
                userSchoolgo.setOpenid(openid);
                schoolgoMapper.insert(userSchoolgo);
            }
        }
        List<UserScientificResearch> researchList = dto.getResearchList();
        if (researchList != null && !researchList.isEmpty()) {
            for (UserScientificResearch research : researchList) {
                research.setOpenid(openid);
                scientificResearchMapper.insert(research);
            }
        }
        List<UserSkill> skillList = dto.getSkillList();
        if (skillList != null && !skillList.isEmpty()) {
            for (UserSkill skill : skillList) {
                skill.setOpenid(openid);
                userSkillMapper.insert(skill);
            }
        }
    }


    /**
     * 修改数据
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public synchronized int updateUserinfoById(UserinfoDTO dto) {
        String openid = dto.getOpenid();
//        WechatUserinfo yuanUserInfo = userinfoMapper.findByOpenid(openid);
//        Integer updateCount = yuanUserInfo.getUpdateCount();
//        if (updateCount-1<0){
//            throw new RuntimeException("已达操作上线");
//        }

        WechatUserinfo userinfo = new WechatUserinfo();
        BeanUtils.copyProperties(dto, userinfo);
        userinfo.setOpenid(openid);
        //先删后增
        motherMapper.deleteByOpenid(openid);
        honorMapper.deleteByOpenid(openid);
        projectMapper.deleteByOpenid(openid);
        educationMapper.deleteByOpenid(openid);
        schoolgoMapper.deleteByOpenid(openid);
        scientificResearchMapper.deleteByOpenid(openid);
        userSkillMapper.deleteByOpenid(openid);
        fatherMapper.deleteByOpenid(openid);
        demandMapper.deleteByOpenid(openid);
        majorRgppMapper.deleteByOpenid(openid);
        addUserInfoQTXX(dto, openid);
        userinfo.setUpdateTime(new Date());
        userinfoMapper.updateById(userinfo);

        return 1;
    }

    /**
     * 删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @Override
    public int removeByUserinfoIds(List<Long> ids) {
        for (Long id : ids) {
            WechatUserinfo userinfo = userinfoMapper.selectById(id);
            userinfoMapper.updateById(userinfo);
        }
        return 1;
    }

    /**
     * 返回可搜索地址
     *
     * @param openid
     * @return
     */
    @Override
    public List<AddressVO> address(String openid) {
        List<UserDemand> demandList = demandMapper.findByOpenid(openid);
        List<AddressVO> addressVOList = new ArrayList<>();
        if (demandList != null && !demandList.isEmpty()) {
            UserDemand demand = demandList.get(0); // 获取第一个需求信息
            String searchLocation = demand.getSearchLocation(); // 意向地点
            String nativePlace = demand.getNativePlace(); // 户籍地
            String graduateCity = demand.getGraduateCity(); // 毕业院校城市
            List<String> areaChList = getAreaChList(searchLocation, nativePlace, graduateCity);
            if (areaChList != null && !areaChList.isEmpty()) {
                for (String address : areaChList) {
                    AddressVO addressVO = new AddressVO();
                    addressVO.setName(address);
                    addressVO.setState(false);
                    addressVOList.add(addressVO);
                }
            } else {
                return new ArrayList<>();
            }
//            List<String> addressList = removeCitySuffix(areaChList);

        } else {
            return new ArrayList<>();
        }
        return addressVOList;
    }

    public static List<String> removeCitySuffix(List<String> areaChList) {
        // 创建一个新的列表，用来存储去除"市"后的城市名称
        List<String> resultList = new ArrayList<>();

        // 遍历原始列表，去除每个城市名称中的"市"
        for (String area : areaChList) {
            // 去除 "市" 字符串
            String cityWithoutSuffix = area.replace("市", "");
            // 将处理后的城市名称添加到新的列表
            resultList.add(cityWithoutSuffix);
        }

        return resultList;
    }

    public List<String> getAreaChList(String searchLocation, String nativePlace, String graduateCity) {
        // 使用LinkedHashSet去重并保持顺序
        Set<String> areaSet = new LinkedHashSet<>();

        // 将用户选择的意向地点分别加入集合
        for (String loc : searchLocation.split(",")) {
//            String ssss = extractCity(loc.trim());
            areaSet.add(loc);
        }
        // 提取户籍地信息 (假设格式为 省市格式)
        // 使用正则或简单的字符串拆分来提取
        String[] parts = nativePlace.split("[,，]");  // 使用正则匹配英文或中文逗号
        if (parts.length > 1) {
            // 将市级信息加入 Set 中
            areaSet.add(parts[1].trim());  // 使用 trim() 去除可能的空格
        }


        // 新一线城市
        List<String> cyx = new ArrayList<>(Arrays.asList("北京市", "上海市", "广州市", "深圳市","杭州市"));
//        List<String> xyx = new ArrayList<>(Arrays.asList("成都市", "重庆市", "杭州市", "武汉市",
//                "苏州市", "西安市", "南京市", "长沙市",
//                "天津市", "郑州市", "东莞市", "青岛市",
//                "昆明市", "宁波市", "合肥市"));

        areaSet.addAll(cyx);
//        areaSet.addAll(xyx);

//        // 将用户选择的地点分别加入集合
//        for (String loc : nativePlace.split(",")) {
//            areaSet.add(loc.trim());
//        }
//        for (String loc : graduateCity.split(",")) {
//            areaSet.add(loc.trim());
//        }

        // 将Set转换为List并返回

        return new ArrayList<>(areaSet);
    }

    private static String extractCity(String areaCn) {
        if (areaCn.endsWith("市")) {
            return areaCn.substring(0, areaCn.length() - 1);  // 去掉"市"字
        }
        return areaCn;  // 如果没有"市"字，直接返回
    }

    // 处理VO数据封装
    private List<UserinfoVO> userinfoVoToList(List<WechatUserinfo> userinfoList) {
        List<UserinfoVO> voList = new ArrayList<>();
        if (userinfoList.size() > 0 && !userinfoList.isEmpty()) {
            for (WechatUserinfo userinfo : userinfoList) {
                UserinfoVO vo = new UserinfoVO();
                BeanUtils.copyProperties(userinfo, vo);
                WechatUser wechatUser = userMapper.findByOpenId(userinfo.getOpenid());
                vo.setHeadimgurl(wechatUser.getHeadimgurl());
                vo.setNickName(wechatUser.getNickname());
                List<UserMajorRgpp> userMajorRgppList = majorRgppMapper.findByOpenid(userinfo.getOpenid());
                if (userMajorRgppList!=null&&!userMajorRgppList.isEmpty()){
                    vo.setUserMajorRgppList(userMajorRgppList);
                }else {
                    vo.setUserMajorRgppList(new ArrayList<>());
                }

                voList.add(vo);
            }
        }
        return voList;
    }


}